import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router, Data } from '@angular/router';
import { BehaviorSubject, of, Observable } from 'rxjs';
import { catchError, map, debounceTime, switchMap } from 'rxjs/operators';
import { Pageable, HttpMethod, UrlPermissionEnum, SparrowUrl, Sysrole, SysroleUrlPermissionPK, SysroleUrlPermission } from 'src/app/domain/sparrow';
import { SparrowApp } from 'src/app/domain/sparrow-app';
import { SparrowAppService } from 'src/app/service/sparrow-app.service';
import { SysroleService } from 'src/app/service/sysrole.service';

@Component({
  selector: 'app-sparrow-app',
  templateUrl: './sparrow-app.component.html',
  styleUrls: ['./sparrow-app.component.css']
})
export class SparrowAppComponent implements OnInit {
  listOfData: SparrowApp[] = [];
  httpMethods: any = [];
  urlPermissions: any = [];
  pageable: Pageable = {page: 0, size: 10}
  total: number = 0;

  constructor(private urlService: SparrowAppService, private fb: FormBuilder, private router: Router, private sysroleService: SysroleService) {
    this.httpMethods = Object.keys(HttpMethod);
    this.urlPermissions = Object.keys(UrlPermissionEnum)

  }
  validateForm!: FormGroup;
  ngOnInit(): void {
    this.urlService.list(this.pageable).subscribe(res => {
      this.listOfCurrentPageData = res.content;
      this.total = res.totalElements;
      console.log(this.total)
    })
  }

  checked = false;
  loading = false;
  indeterminate = false;
  // listOfData: readonly Data[] = [];
  listOfCurrentPageData: readonly Data[] = [];
  setOfCheckedId = new Set<string>();

  updateCheckedSet(id: string, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onCurrentPageDataChange(listOfCurrentPageData: readonly Data[]): void {
    this.listOfCurrentPageData = listOfCurrentPageData;
    this.refreshCheckedStatus();

  }
  onPageIndexChange(page: number) {
    this.pageable.page = page;
    this.urlService.list(this.pageable).subscribe(res => {
      this.total = res.totalElements;
      this.listOfCurrentPageData = res.content;
      this.setOfCheckedId.clear()
      // this.listOfData = res.content;
    })
  }

  onPageSizeChange(size: number) {
    this.pageable.size = size;
    this.urlService.list(this.pageable).subscribe(res => {
      this.total = res.totalElements;
      this.listOfCurrentPageData = res.content;
      this.setOfCheckedId.clear()
      // this.listOfData = res.content;
    })
  }

  refreshCheckedStatus(): void {
    const listOfEnabledData = this.listOfCurrentPageData.filter(({ disabled }) => !disabled);
    this.checked = listOfEnabledData.every(({ id }) => this.setOfCheckedId.has(id));
    this.indeterminate = listOfEnabledData.some(({ id }) => this.setOfCheckedId.has(id)) && !this.checked;
  }

  onItemChecked(id: string, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(checked: boolean): void {
    this.listOfCurrentPageData
      // .filter(({ system }) => !system)
      .forEach(({ id }) => this.updateCheckedSet(id, checked));
    this.refreshCheckedStatus();
  }

  onDelete() {
    console.log(Array.from(this.setOfCheckedId));
    this.urlService.delete(Array.from(this.setOfCheckedId)).subscribe(res => {
      this.urlService.list(this.pageable).subscribe(res => {
        this.total = res.totalElements;
        this.listOfCurrentPageData = res.content;
        // this.listOfData = res.content;
      })
    });
    this.refreshCheckedStatus();
  }




  isVisible = false;

  showModal(): void {
    let url: SparrowUrl;
    this.isVisible = true;
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      code: [null, [Validators.required]],
      remark: [null, null],
    });
  }




  handleOk(): void {
    console.log('Button ok clicked!');
    // for (const i in this.validateForm.controls) {
    //   console.log(this.validateForm.value)
    // }
    this.isVisible = false;
    let url: SparrowUrl = this.validateForm.value;
    console.log(url)
    let urls: SparrowUrl[] = [];
    urls.push(this.validateForm.value)
    this.urlService.save(urls).subscribe(res => {

    })
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }

  submitForm(): void {
    if (!this.validateForm.valid) {
      for (const i in this.validateForm.controls) {
        if (this.validateForm.controls.hasOwnProperty(i)) {
          this.validateForm.controls[i].markAsDirty();
          this.validateForm.controls[i].updateValueAndValidity();
        }
      }
    } else {
      let urls: SparrowUrl[] = [];
      urls.push(this.validateForm.value);
      this.urlService.save(urls).subscribe(res => {
        this.isVisible = false;
      })
    }
  }

  onClose() {

  }

  handlePermissionCancel() {
    this.isVisibleForPermission = false;
  }

  // for permission
  randomUserUrl = 'https://api.randomuser.me/?results=5';
  searchChange$ = new BehaviorSubject('');
  optionList: Sysrole[] = [];
  selectedUser?: Sysrole[];
  isLoading = false;

  onSearch(value: string): void {
    this.isLoading = true;
    this.searchChange$.next(value);
  }
  isVisibleForPermission = false;

  selectedUrls: SparrowUrl[] | any = [];
  setUrlPermission() {
    this.selectedUser = [];
    // this.isVisibleForPermission = true;
    // console.log(Array.from(this.setOfCheckedId))
    this.selectedUrls = this.listOfCurrentPageData.filter(f => this.setOfCheckedId.has(f.id));
    // let urltree = this.router.createUrlTree(["/urlPermission",{ids:JSON.stringify( Array.from(this.setOfCheckedId))}]);
    // this.router.navigateByUrl(urltree);
    const getRandomNameList = (name: string) =>
      this.sysroleService.list({page: 0, size: 10})
        .pipe(
          catchError(() => of({ results: [] })),
          map((res: any) => res.content)
        )
        // .pipe(map((list: any) => list.map((item: any) => `${item.name}`)));
    const optionList$: Observable<Sysrole[]> = this.searchChange$
      .asObservable()
      .pipe(debounceTime(500))
      .pipe(switchMap(getRandomNameList));
    optionList$.subscribe(data => {
      this.optionList = data;
      this.isLoading = false;
    });
    this.isVisibleForPermission = true;
  }

  addPermission() {
    let pks:SysroleUrlPermissionPK[] = [];
    this.selectedUrls.forEach((url: { id: any; }) => {
      this.selectedUser?.forEach(user=>{
        let pk:SysroleUrlPermissionPK = new SysroleUrlPermissionPK();
        pk.sysroleId = user.id
        pk.urlId = url.id
        pks.push(pk)
      })
    });
    this.urlService.addPermission(pks).subscribe(res=>{
      this.isVisibleForPermission = false;
    })
  }

  delPermission() {
    let pks:SysroleUrlPermissionPK[] = [];
    this.selectedUrls.forEach((url: { id: any; }) => {
      this.selectedUser?.forEach(user=>{
        let pk:SysroleUrlPermissionPK = new SysroleUrlPermissionPK();
        pk.sysroleId = user.id
        pk.urlId = url.id
        pks.push(pk)
      })
    });
    this.urlService.delPermission(pks).subscribe(res=>{
      this.isVisibleForPermission = false;
    })
  }

  currentPermissions: SysroleUrlPermission[] = [];

  isVisibleForCheckPermission:boolean = false;
  checkUrlPermission(){
    this.urlService.getPermissionById(Array.from(this.setOfCheckedId)).subscribe(res => {
      this.currentPermissions = res.content
      this.isVisibleForCheckPermission = true;
    })
  }

  handleCheckPermissionCancel(){
    this.isVisibleForCheckPermission = false;
  }
}
